# -*- coding: utf-8 -*-

#This project is licensed under the Apache License Version 2.0

#author: wycharon@gmail.com

#一些工具类和函数

import os
import sys,codecs
import logging,logging.handlers

LINELENGTH = 60
iseq = range(9999)  #用于在list迭代中得到下标,如 [i for i,v in zip(iseq,sourcelist)] 将得到一个index列表

#两个临时文件的帮助函数. mktemp根据txt生成一个临时文件，removetemp删除这个临时文件
def mktemp(txt):
    from tempfile import mkstemp
    tpair = mkstemp()
    file(tpair[1],'w+').write(txt)
    return {'fd':tpair[0],'name':tpair[1]}

def removetemp(temp):
    import os
    os.close(temp['fd'])
    os.remove(temp['name'])

def parseName(filename):#去掉文件扩展名并获得不含路径的文件名，如c:\aaa\bbb.txt变为bbb,而bbb.txt也变为bbb
    return os.path.splitext(os.path.basename(filename))[0] 

log_handlers = []
def logging_config(mainfile,summaryfile=None,mainlevel = logging.DEBUG,summarylevel=logging.WARNING):
    ''' 配置logging
        mainfile为主要文件，用于记录mainlevel以上信息，采用轮换方式
        summaryfile为概要文件，用于记录概要信息
    '''
    rootlogger = logging.getLogger()
    for handler in log_handlers:    #移除之前的handlers
        rootlogger.removeHandler(handler)
        #print 'closing:',handler.baseFilename
        handler.close()    
        #print 'closed:',handler.baseFilename
    log_handlers[:] = []    #清空，并避免global声明
    rootlogger.setLevel(mainlevel)    #最低级别
    hmainfile = logging.handlers.RotatingFileHandler(mainfile,maxBytes=1024000,backupCount=3)
    hmainfile.setFormatter(logging.Formatter('%(name)s:%(funcName)s:%(lineno)d: %(asctime)s %(levelname)s %(message)s'))
    rootlogger.addHandler(hmainfile)
    log_handlers.append(hmainfile)
    if(summaryfile):
        hsummary =  logging.FileHandler(summaryfile)
        hsummary.setLevel(summarylevel)
        hsummary.setFormatter(logging.Formatter('%(name)s:%(funcName)s:%(lineno)d: %(asctime)s %(levelname)s %(message)s'))
        rootlogger.addHandler(hsummary)
        log_handlers.append(hsummary)


def linelog(msg):   #在同一行覆盖显示日志输出
    sys.stdout.write(unicode((u'\r%s%s' % (msg,' ' * (LINELENGTH - len(msg)))))) #.encode('gbk'))  #适应输出编码为gbk

def writerecord(filehandler,record):    #用于循环的话比较浪费,基本不用于循环，只用于单行记录
    format_string = (u'%s,' * len(record))[:-1] + '\n'
    filehandler.write(format_string % record)

def writerecords(filehandler,*args):    
    ''' 用于多个列表的同步输出，通常用于运算脚本的测试中
        args必须都是列表
    '''
    length = len(args)
    assert length > 0
    format_string = (u'%s,' * length)[:-1] + '\n'
    for record in zip(*args):
        filehandler.write(format_string % record)
